package logic

import (
	"cart-master/cache"
	"cart-master/cartrpc/cartrpc"
	"cart-master/cartrpc/internal/svc"
	"cart-master/model"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *cartrpc.LoginRequest) (*cartrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user model.User
	model.DB.Debug().Where("tel=?", in.Tel).First(&user)
	if user.ID == 0 {

		user = model.User{
			Tel:      in.Tel,
			Password: in.Password,
		}

		result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Tel).Result()
		if result != in.SendSms {
			return nil, fmt.Errorf("验证码错误")
		}
		model.DB.Debug().Create(&user)
	}
	if in.Password != user.Password {

		return nil, fmt.Errorf("密码错误")
	}
	return &cartrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
